package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: my-tanhua
 * @description:
 * @author: xuejingjing
 * @create: 2021-10-07 11:33
 **/

@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

     private static final String REDIS_KEY  =  "HX_TOKEN";

     @Autowired
     private HuanXinConfig huanXinConfig;
    /**
     * 获取token,先从redis中获取，如果没有，再去环信中获取
     * @return
     */
      public String getToken(){
          String token = redisTemplate.opsForValue().get(REDIS_KEY);
          if(StrUtil.isNotBlank(token)){
              return token;
          }
          //为空
          //访问环信接口获取token
          return refreshToken();


      }
      private String refreshToken(){
          String targetUrl = huanXinConfig.getUrl() +huanXinConfig.getOrgName() +"/"+
                  huanXinConfig.getAppName() +"/token";
          Map<String,Object> param = new HashMap<>();
          param.put("grant_type","client_credentials");
          param.put("client_id",huanXinConfig.getClientId());
          param.put("client_secret",huanXinConfig.getClientSecret());
          HttpResponse response = HttpRequest.post(targetUrl)
                  .body(JSONUtil.toJsonStr(param))
                  .timeout(20000)
                  .execute();

          if(!response.isOk()){
              return null;
          }
          String jsonBody = response.body();
          JSONObject jsonObject = JSONUtil.parseObj(jsonBody);
          String token = jsonObject.getStr("access_key");
          if(StrUtil.isNotEmpty(token)){
              //将token缓存到redis中，缓存时间由expiress_in决定
              //提前1小时失效
              jsonObject.getLong(expires_in)- 3600;
              redisTemplate.opsForValue().set(REDIS_KEY,token,timeout, TimeUnit.SECONDS);
              return token;
          }
           return null;
      }
}